package com.example.black.myapplication;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class WrapRecycleView extends RecyclerView {
    List<View> mHeaderViewInfos = new ArrayList<>();
    List<View> mFooterViewInfos = new ArrayList<>();
    private Adapter mAdapter;
    public WrapRecycleView(Context context) {
        this(context,null);
    }

    public WrapRecycleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public WrapRecycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void addHeaderView(View v) {

        mHeaderViewInfos.add(v);

        // Wrap the adapter if it wasn't already wrapped.
        if (mAdapter != null) {
            if (!(mAdapter instanceof WrapAdapter)) {
                wrapHeaderListAdapterInternal();
            }
        }
    }

    public void addFooterView(View v) {

        mFooterViewInfos.add(v);

        // Wrap the adapter if it wasn't already wrapped.
        if (mAdapter != null) {
            if (!(mAdapter instanceof WrapAdapter)) {
                wrapHeaderListAdapterInternal();
            }
        }
    }

    private void wrapHeaderListAdapterInternal() {
        mAdapter = wrapHeaderListAdapterInternal(mHeaderViewInfos, mFooterViewInfos, mAdapter);
    }
    protected WrapAdapter wrapHeaderListAdapterInternal(
            List<View> headerViewInfos,
            List<View> footerViewInfos,
            Adapter adapter) {
        return new WrapAdapter(adapter,headerViewInfos, footerViewInfos);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
            mAdapter = new WrapAdapter(adapter,mHeaderViewInfos, mFooterViewInfos);
        } else {
            mAdapter = adapter;
        }
        super.setAdapter(mAdapter);
    }
}
